package com.example.forum.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.forum.entity.TSensitivewords;
import com.example.forum.mapper.TSensitivewordsMapper;
import com.example.forum.mapper.TUsersMapper;
import com.example.forum.service.ITSensitivewordsService;
import com.example.forum.vo.ImportFileReturnDto;
import com.example.forum.vo.SenctiveWordsDto;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author why
 * @since 2020-04-22
 */
@Service
public class TSensitivewordsServiceImpl extends ServiceImpl<TSensitivewordsMapper, TSensitivewords> implements ITSensitivewordsService {

    @Autowired
    private TUsersMapper usersMapper;

    @Override
    public boolean insertTSensitiveWords(TSensitivewords tSensitivewords) {


        int insert = this.baseMapper.insert(tSensitivewords);
        return insert == 1;
    }


    @Override
    public boolean deleteSensitiveWords(SenctiveWordsDto senctiveWordsDto, String currentUserId) {
        //判断当前用户是否存在
        if (usersMapper.selectById(currentUserId) == null) {
            return false;
        }
        //删除
        for (String wordId : senctiveWordsDto.getWordIds()) {
            TSensitivewords sensitivewords = baseMapper.selectById(wordId);
            sensitivewords.setIsdeleted(senctiveWordsDto.getIsDeleted());
            sensitivewords.setDeletiontime(DateTime.now());
            sensitivewords.setDeleteruserid(currentUserId);
            //更新
            baseMapper.updateById(sensitivewords);
        }
        return true;
    }


    @Override
    public ImportFileReturnDto importExcel(MultipartFile file, String currentUserId) {

        if (file.isEmpty()) {
            return new ImportFileReturnDto("文件为空", false);
        }
        if (file.getSize() > 1048576000) {
            return new ImportFileReturnDto("文件过大", false);
        }
        //判断文件类型
        ArrayList<String> fileType = new ArrayList<>();
        fileType.add("xls");
        fileType.add("xlsx");
        //上传的文件名
        System.out.println(file.getOriginalFilename());
        String name = file.getOriginalFilename();
        String[] split = name.split("\\.");
        boolean sss = fileType.contains(split[1]);
        if (!sss) {
            return new ImportFileReturnDto("文件格式错误", false);
        }
        //分析表格数据
        ArrayList<String> words = null;
        try {
            words = getSheetValues(file);
        } catch (IOException e) {
            e.printStackTrace();
            return new ImportFileReturnDto("获取数据异常" + e.getMessage(), false);
        }
        if (words == null) {
            return new ImportFileReturnDto("表格无数据", false);
        }
        //上传成功 根据名称获取数据
        //获取原有的敏感词
        List<String> terms = baseMapper.selectList(new QueryWrapper<TSensitivewords>().eq("isDeleted", 0))
                .stream().map(TSensitivewords::getTerms).collect(Collectors.toList());
        for (String word : words) {
            //不存在就新增
            if (!terms.contains(word)) {
                TSensitivewords tSensitivewords = new TSensitivewords();
                tSensitivewords.setTerms(word);
                tSensitivewords.setIsdeleted(false);
                tSensitivewords.setLevel(1);
                tSensitivewords.setIsrelease(false);
                tSensitivewords.setCreatoruserid(currentUserId);
                baseMapper.insert(tSensitivewords);
            }

        }

        return new ImportFileReturnDto("上传成功", true);

    }

    private ArrayList<String> getSheetValues(MultipartFile file) throws IOException {
        Workbook workbook = null;
        // HSSFWorkbook是针对.xls文件，XSSFWorkbook是针对.xslx文件。
        if (file.getOriginalFilename().contains(".xlsx")) {
            workbook = new XSSFWorkbook(file.getInputStream());
        } else {
            workbook = new HSSFWorkbook(file.getInputStream());
        }
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            return null;
        }
//        sheet.getRow(1).getCell(2).getStringCellValue();
        ArrayList<String> words = new ArrayList<>();
        //遍历行row   getLastRowNum从0开始算
        //从第二行开始为敏感词
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            //遍历列
            System.out.println(sheet.getRow(i).getLastCellNum());
            int cellNum = sheet.getRow(i).getLastCellNum();
                    if (cellNum!=-1) {
                        for (int j = 0; j < cellNum; j++) {
                            Cell cell = sheet.getRow(i).getCell(j);
                            if (cell != null) {
                                String stringCellValue = cell.getStringCellValue();
                                words.add(stringCellValue);
                            }
                }
            }

        }
        return words;
    }
}
